package rpg.data;

import java.io.File;
import java.util.List;

import org.jdom.Element;

import pedrosm.data.ScriptData;
import pedrosm.utils.Debug;

import square.data.CreatureData;
import square.data.DataGroup;
import square.data.SpriteData;
import square.script.CreatureScript;

/**
 * 
 * @author Pedro Silva Moreira
 */
public class CreatureXML implements LoaderXML {
	private static CreatureXML singleton = new CreatureXML();
	
	// Creation
	private CreatureXML() {
	}
	
	// Instance
	public static CreatureXML instance() {
		return singleton;
	}
	
	// Load
	public void load(String group, String name, Element origin) {
		Element elem = XML.loadXML(XML.DATA_FOLDER + "creatures" + File.separator
				+ group + File.separator + name + ".xml");

		CreatureData data = new CreatureData();
		data.setName(elem.getAttributeValue("name"));

		SpriteData sprite = DataGroup.findSprite(elem.getAttributeValue("sprite"));
		if (sprite == null) {
			Debug.debug("CreatureXML", "Failed to create CreatureData with sprite: "
					+ elem.getAttributeValue("sprite"));
			return;
		}
		
		data.setSprite(sprite);
		parseData(elem, data);
		DataGroup.getCreatures().add(data);
	}

	@SuppressWarnings("unchecked")
	public static void parseData(Element elem, CreatureData data) {
		String script = elem.getAttributeValue("script");
		if(script != null)
			data.setScript((ScriptData<CreatureScript>) DataGroup.findScript(script));
		
		List<Element> attributes = elem.getChildren("attr");
		for (Element attr : attributes) {
			String name = attr.getAttributeValue("name");
			String value = attr.getAttributeValue("value");

			if(name.equals("experience")) {
				data.setExperience(Integer.valueOf(value));
			} else if (name.equals("level")) {
				data.setLevel(Integer.valueOf(value));
			} else if (name.equals("health")) {
				data.setHealth(Integer.valueOf(value));
			} else if (name.equals("maxHealth")) {
				data.setMaxHealth(Integer.valueOf(value));
			} else if (name.equals("mana")) {
				data.setMana(Integer.valueOf(value));
			} else if (name.equals("maxMana")) {
				data.setMaxMana(Integer.valueOf(value));
			} else if (name.equals("attack")) {
				data.setAttack(Integer.valueOf(value));
			} else if (name.equals("defense")) {
				data.setDefense(Integer.valueOf(value));
			} else if (name.equals("magic")) {
				data.setMagic(Integer.valueOf(value));
			} else if (name.equals("speed")) {
				data.setSpeed(Integer.valueOf(value));
			} else if (name.equals("critical")) {
				data.setCritical(Integer.valueOf(value));
			} else if (name.equals("range")) {
				data.setRange(Integer.valueOf(value));
			} else if (name.equals("follow")) {
				data.setFollow(value);
			} else if (name.equals("aggressive")) {
				data.setAggressive(Boolean.valueOf(value));
			}
		}

		// Skill
		List<Element> skills = elem.getChildren("skill");
		for(Element skill : skills) {
			String name = skill.getAttributeValue("name");
			data.getSkills().add(DataGroup.findSkill(name));
		}
	}
}
